<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ page.total }}条数据</span>
        <span slot="after">
          <el-button
            type="success"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="exportData"
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            :disabled="!checkPermission('POINT-USER-ADD')"
            @click="addDialog"
          >新增</el-button>
        </span>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            sortable=""
            type="index"
            align="center"
            width="50"
          />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center" width="120">
            <template slot-scope="scope">
              <img
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                :src="scope.row.staffPhoto"
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                @click="showQrCode(scope.row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- 作用域插槽 -->
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                :disabled="!checkPermission('POINT-USER-UPDATE')"
                type="text"
                size="small"
                @click="$router.push(`employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                v-if="checkPermission('abc')"
                type="text"
                size="small"
                @click="assignRole(row.id)"
              >角色</el-button>
              <el-button
                :disabled="!checkPermission('point-user-delete')"
                type="text"
                size="small"
                @click="deleteEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- // 放置分页组件 -->
        <el-row
          type="flex"
          justify="center"
          style="height: 60px"
          align="middle"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            :current-page.sync="page.page"
            @current-change="newPage"
          />
        </el-row>
      </el-card>
    </div>
    <!-- // 新增员工弹层 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- // 二维码弹层 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 分配角色弹层 -->
    <assign-role
      ref="assignDia"
      :user-id="userId"
      :dialog-visible.sync="dialogVisible"
    />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import addEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  components: { addEmployee, AssignRole },
  data() {
    return {
      list: [], // 接收所有员工信息列表
      page: {
        page: 1, // 当前页码
        size: 5, // 每页显示数量
        total: 0, // 总数
        abc: 3
      },
      loading: false, // 进度条
      showDialog: false,
      showCodeDialog: false,
      dialogVisible: false, // 分配角色弹层开关
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 点击角色弹出弹出分配权限
    async assignRole(id) {
      await this.$refs.assignDia.getUserDetailById(id)
      this.userId = id
      this.dialogVisible = true
    },
    // 点击头像生成二维码
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 导出员工数据
    exportData() {
      //  做操作
      // 表头对应关系
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        用户id: 'departmentId',
        部门: 'departmentName'
      }
      const merges = ['A1:A2', 'B1:G1', 'H1:H2']
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '', '部门']]
      import('@/vendor/Export2Excel').then(async(excel) => {
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total
        })
        const data = this.formatJson(headers, rows)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填 (导出的类型 xlsx, csv, txt, )
          multiHeader, // 复杂表头
          merges // 合并单元格
        })
      })
    },
    // 点击新增员工
    addDialog() {
      this.showDialog = true
    },
    // 获取所有员工信息
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    // 点击分页页码重新渲染数据
    newPage(newval) {
      this.page.page = newval
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工信息
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定要删除该员工吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delEmployee(id)
        await this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 格式化导出员工数据
    formatJson(arr, rows) {
      return rows.map((item) => {
        // item为对象 {username:'张三',mobile:133333}
        return Object.keys(arr).map((obj) => {
          // 此时的Object.keys(arr) 为[姓名,手机号,入职日期]
          if (arr[obj] === 'timeOfEntry' || arr[obj] === 'correctionTime') {
            return formatDate(item[arr[obj]])
          } else if (arr[obj] === 'formOfEmployment') {
            const val = EmployeeEnum.hireType.find(
              (key) => key.id === item[arr[obj]]
            )
            return val ? val.value : '未知'
          }
          return item[arr[obj]]
        })
      })
      // return rows.map((item) => Object.keys(arr1).map((key) => item[arr1[key]]))
    }
  }
}
</script>

<style></style>
